import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import { showScreenLoading, hideScreenLoading } from "./loading";
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 15000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (config.headers.showLoading !== false) {
      showScreenLoading(config.headers);
    }
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // 将Token传到浏览器请求头Authorization上 
      config.headers['Authorization'] = 'Bearer ' + getToken();
    }
    return config
  },
  error => {
    hideScreenLoading(config.headers);
    console.log(error,100) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {

    if (response.headers.showLoading !== false) {
      hideScreenLoading();
    
    let isdownload = response.request.responseURL.indexOf('download') //下载接口没有StatusCode
    let isupload = response.request.responseURL.indexOf('upload') //下载接口没有StatusCode
    const res = response.data
    // isdownload === -1 && isupload === -1 && 
    if (res.Status.StatusCode !== 0) {
      if (res.Status.StatusCode === 2000) {
        Message({
          message: '登录会话已超时，即将跳转到登录页......',
          type: 'error',
          duration: 3 * 1000,
          customClass: 'message-override'
        })
        setTimeout(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        }, 3000)
        // to re-login
        // MessageBox.confirm('登录状态已失效，是否重新登录', {
        //   confirmButtonText: '重新登录',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(() => {
        //   store.dispatch('user/resetToken').then(() => {
        //     location.reload()
        //   })
        // })
      }else if(res.Status.StatusCode === 256){  //邮箱测试接口返回256，错误0x100
        return res
      }else if (res.Status.StatusCode != 0){
        Message({
          message: res.Status.Msg2Client || 'Error',
          type: 'error',
          duration: 5 * 1000,
          customClass: 'message-override'
        })
        return Promise.reject(res)
      }
      // else if(res.Status.StatusCode === 8467){
      //   // MessageBox.confirm('检测到该用户首次登录，请修改密码后重新登录', {
      //   //   confirmButtonText: '修改密码',
      //   //   cancelButtonText: '取消',
      //   //   type: 'warning'
      //   // }).then(() => {
          
      //   // })
      //   MessageBox.prompt('检测到该用户首次登录，请修改密码后重新登录', '提示', {
      //     confirmButtonText: '修改密码',
      //     cancelButtonText: '取消',
      //     inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
      //     inputErrorMessage: '密码格式不正确'
      //   }).then(({ value }) => {
      //     Message({
      //       type: 'success',
      //       message: '修改成功，请重新登录'
      //     });
      //   }).catch(() => {
      //     Message({
      //       type: 'info',
      //       message: '取消输入'
      //     });       
      //   });
      // }
      else{
        return res
      }
      
    } else {
      
      return res
    }
  }
},
  error => {
    hideScreenLoading();
    console.log('err' + error) // for debug
    if(error.message.includes('timeout')){
      Message({
        message: '命令后台执行超时，请缩小或优化过滤条件',
        type: 'error',
        duration: 5 * 1000
      })
    }else{
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    
    return Promise.reject(error)
  }
)

export default service
